package com.fandou.airobot.ui.recording;

import android.graphics.Bitmap;

import com.fandou.base.utils.BitmapUtil;
import com.fandou.videocreator.IProviderExpand;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BitmapProvider implements IProviderExpand<Bitmap> {
    private int index = 0;
    private Queue<byte[]> queue;

    private List<String> paths;
    private int[] scaleSize;

    public BitmapProvider(List<String> paths, int[] scaleSize) {
        this.paths = paths;
        this.scaleSize = scaleSize;
        queue = new LinkedList<>();
    }

    public void init() {
        for (int i = 0; i < paths.size(); i++) {
            String path = paths.get(i);
            if (!new File(path).exists()) {
                continue;
            }
            Bitmap bitmap = genBitmap(path);
            if (bitmap == null) {
                continue;
            }
            queue.add(BitmapUtil.getBytesByJPG(bitmap));
            bitmap.recycle();
        }
    }

    public boolean isAvailable() {
        return !queue.isEmpty();
    }

    @Override
    public void prepare() {
    }

    @Override
    public void finish() {
    }

    @Override
    public void finishItem(Bitmap item) {
//        item.recycle();
//        System.gc();
    }

    @Override
    public boolean hasNext() {
        return index < paths.size();
    }

    @Override
    public int size() {
        return paths.size();
    }

    private Bitmap genBitmap(String path) {
        return BitmapUtil.decodeSampleBitmapFromResource(path, scaleSize[0], scaleSize[1]);
    }

    @Override
    public Bitmap next() {
        byte[] bytes = queue.poll();
        index++;
        return BitmapUtil.loadFromBytesByPNG(bytes);
    }
}
